import { mapState, mapActions } from 'vuex'
import { makeUUID } from '@/utils'

export default {
  data() {
    return {
      // 当前被观察的图元
      observeSubject: 0,
      observerName: ''
    }
  },
  computed: {
    ...mapState('editor/diagram', {
      // 时间戳
      _subjectStamp(state) {
        if (this.observerName === '') {
          return ''
        } else {
          if (!state.observeState.hasOwnProperty(this.observerName)) {
            return ''
          } else {
            return state.observeState[this.observerName].stamp
          }
        }
      },
      // 观察的目标
      _subjects(state) {
        if (this.observerName === '') {
          return []
        } else {
          if (!state.observeState.hasOwnProperty(this.observerName)) {
            return []
          } else {
            return state.observeState[this.observerName].subjects
          }
        }
      }
    })
  },
  watch: {
    // 监控时间戳
    _subjectStamp: {
      handler(newVal, oldVal) {
        // console.log('watch --> subjectStamp:', oldVal, ' --> ', newVal)
        if (newVal !== '') {
          this.onSubjectChange(this._subjects)
        }
      },
      // https://www.cnblogs.com/shiningly/p/9471067.html
      // 第一次绑定的时候，不会执行监听函数，只有值发生改变才会执行。
      // 如果我们需要在最初绑定值的时候也执行函数，则就需要用到immediate属性
      immediate: false
    }
  },
  methods: {
    ...mapActions('editor/diagram', {
      _updateSubjects: 'updateSubjects'
    }),
    // 给vue组件提供接口,触发更新
    updateSubjects(subjects) {
      if (
        this.observerName !== null &&
        this.observerName !== undefined &&
        this.observeName !== ''
      ) {
        this._updateSubjects({
          stamp: makeUUID(),
          observer: this.observerName,
          subjects
        })
      }
    },
    // 被观察图元的数据发生了变化
    onSubjectChange(parts) {}
  }
}
